package com.huhao.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class SemaphoreExample1 {

    //线程总数
    public static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();

        //最大并发数20
        final Semaphore semaphore = new Semaphore(20);

        for (int index = 0; index < threadTotal; index++) {
            final int threadNum = index;
            exec.execute(() -> {
                try {

                    //线程请求，如果线程数已经到了，可能会阻塞，等有线程释放了再执行
                    semaphore.acquire();
                    add(threadNum);
                    //add执行完后，释放当前线程
                    semaphore.release();

//                    //尝试获取一个许可，获取不到就拉倒，获取到了就执行
//                    if (semaphore.tryAcquire()) {
//                        add(threadNum);
//                        semaphore.release(); //释放-一个许可
//                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        //等已有线程都执行完，再关闭线程池
        exec.shutdown();
        log.error("finish");
    }

    private static void add(int threadNum) throws InterruptedException {
        log.info("{}", threadNum);
        Thread.sleep(1000);
        //线程睡1秒，并发数为20，所以效果是会1秒钟放行20个线程，打印20个。。。10秒打印完
    }
}
